let http = require("http");
let crypto = require("crypto");
let { spawn } = require("child_process");
let secret = "123456";
function sign(timestamp) {
  let sign = timestamp + "\n" + secret;
  return crypto.createHmac("sha256", secret).update(sign).digest("hex");
}
let server = http.createServer(function (req, res) {
  console.log(req.method, req.url);
  if (req.method == "POST" && req.url == "/webhook") {
    let buffers = [];
    req.on("data", function (buffer) {
      buffers.push(buffer);
    });
    req.on("end", function () {
      let body = Buffer.concat(buffers);
      let event = req.headers["x-gitee-event"];
      let token = req.headers["x-gitee-token"];
      let timestamp = req.headers["x-gitee-timestamp"];
    //   console.log(token, timestamp, sign(timestamp), "-=-=mimi-=-=");
      if (
        crypto
          .createHmac("sha256", token)
          .update(timestamp + "\n" + token)
          .digest("hex") !== sign(timestamp)
      ) {
        console.log("not allowed");
        return res.end("not allowed");
      }
      res.setHeader("Content-Type", "application/json");
      res.end(JSON.stringify({ ok: true }));
      console.log(event.toLowerCase().toString(), event.toLowerCase().toString().includes("push"),"-=-=");
      if (event.toLowerCase().toString().includes("push")) {
        let payload = JSON.parse(body);
        // https://gitee.com/help/articles/4186#article-header2
        // console.log(payload, "payload");
        let child = spawn("sh", [`./${payload.repository.name}.sh`]);
        let buffes = [];
        child.stdout.on("data",function(chunk) {
            buffes.push(chunk);
        })
        child.stdout.on("end",function() {
            let log = Buffer.concat(buffes);
            console.log(log);
        })
      }
    });
  } else {
    res.end("not found");
  }
});
server.listen(4000, () => {
  console.log("webhook server running 4000");
});
